package com.doge.calcalbum.business.trash

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.doge.calcalbum.R
import com.doge.calcalbum.business.ITEM_CHECK
import com.doge.calcalbum.core.base.adapters.AdapterCallback
import com.doge.calcalbum.core.base.adapters.ITEM_CLICKED
import com.doge.calcalbum.core.base.adapters.ITEM_LONG_CLICKED
import com.doge.calcalbum.databinding.CellTrashEntryBinding
import com.doge.calcalbum.db.model.Entry
import com.doge.calcalbum.utils.*
import kotlin.math.max

class TrashEntryViewHolder(
    parent: ViewGroup,
    callback: AdapterCallback,
    val binding: CellTrashEntryBinding = CellTrashEntryBinding.inflate(
        LayoutInflater.from(parent.context),
        parent,
        false
    ),
) : RecyclerView.ViewHolder(binding.root) {


    init {
        binding.item.setOnClickCallback {
            callback.invoke(ITEM_CLICKED, itemView.tag)
        }
        binding.item.setOnLongClickListener {
            callback.invoke(ITEM_LONG_CLICKED, itemView.tag)
            true
        }
        binding.checkbox.setOnClickListener {
            callback.invoke(ITEM_CHECK, itemView.tag)
        }
    }

    @SuppressLint("SetTextI18n")
    fun bind(item: Entry) {
        itemView.tag = item
        binding.cover.load(item.filePath)

        val leftDay = leftDay(item.deleteTime)
        binding.trashLeftTime.text = "${leftDay}天"
        binding.trashLeftTime.setTextColor(getColor(if (leftDay <= 3) "#F76166" else "#ffffff"))

        binding.checkbox.isVisible = item.selected != null

        binding.checkbox.tag = item.selected
        binding.checkbox.setImageResource(
            if (item.selected == true) R.mipmap.check_selected else R.mipmap.check_normal
        )
        binding.checkboxShadow.isVisible = item.selected == true

    }

    private fun leftDay(timestamp: Long?): Int {
        if (timestamp == null) return 0
        val expiredTimestamp = System.currentTimeMillis() + TRASH_CLEAR_DELAY_TIME
        return max(0, ((expiredTimestamp - timestamp) / (24 * 60 * 60 * 1000L)).toInt())
    }
}